package com.lube;

import java.io.File;

import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * TCP服务端
 * 
 * @author caizhiping
 * @date 2017年1月24日 下午2:04:29
 */
public class Server {
	private static final Logger LOG = LogManager.getLogger(Server.class);

	public Server() {
		start();
	}

	/**
	 * 启动服务
	 */
	public void start() {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workGroup = new NioEventLoopGroup();
		try {
			Configurations configs = new Configurations();
			Configuration config = configs.properties(new File("netty.properties"));
			String ip = config.getString("tcp.server_ip");
			int port = config.getInt("tcp.server_port");

			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workGroup);
			b.channel(NioServerSocketChannel.class);
			b.option(ChannelOption.SO_BACKLOG, 128);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.childHandler(new ServerInitializer());

			ChannelFuture future = b.bind(ip, port).sync();

			LOG.info("服务启动成功,ip={},port={}", ip, port);

			future.channel().closeFuture().sync();
		} catch (Exception e) {
			LOG.error("服务启动失败", e);
			System.exit(1);
		} finally {
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) {
		try{
			new Server();
		}catch (Exception e) {
			LOG.error(e);
		}
		
	}
}
